﻿using Caliburn.Micro;
using MCPlatform.Builder.WorkStation.StationEvents;
using MCPlatform.Builder.WorkStation.StationEvents.Product;
using MCPlatform.Models;
using MCPlatform.MotionLib.Base.AssitantClass;
using MCPlatform.MotionLib.Base.Environment;
using MCPlatform.MotionLib.Base.Models;
using MCPlatform.UI.Components;
using MCPlatform.UI.Controls.Views;
using MCPlatform.ViewModels.Dxf;
using Microsoft.Win32;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MCPlatform.ViewModels.Product
{
    public class ProductViewModel:ViewModelBase
    {
        public ObservableCollection<ProductModel> ProductModels { get; set; } = new ObservableCollection<ProductModel>();

        public static event System.Action<ProductModel>? SaveEvent;

        public static event System.Action<ProductModel>? DeleteEvent;

        public static event System.Action<string,string>? RenameEvent;

        public ProductModel SelectedProductModel
        {
            get => _SelectedProductModel;
            set
            {
                Set(ref _SelectedProductModel, value);

            }
        }

        private ProductModel _SelectedProductModel = new ProductModel();


      
            

        //public ToolModel ToolModel
        //{
        //    get => _ToolModel;
        //    set
        //    {
        //        Set(ref _ToolModel, value);

        //    }
        //}

        //private ToolModel _ToolModel = new ToolModel();


        
        public ProductModel SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (value is null)
                {
                    return;
                }
                Set(ref _selectedItem, value);
                SelectedProductModel = value;
                SetAllProductUnselected();
                SelectedProductModel.IsLastSelected = true;
            }
        }
        private ProductModel _selectedItem = new ProductModel();


        public ProductViewModel()
        {          
            Load();
        }


        public void ToolApply()
        {
            ConfigApply();
        }

        public void UnloadApply()
        {
            ConfigApply();
        }

        public void CuttingApply()
        {
            ConfigApply();
        }

        public  void ConfigApply()
        {
           

            if (ProductModels.Count > 0)
            {
                SaveConfigData.SaveConfig<ProductModel>(Paths.ProductConfigPaths, ProductModels.ToArray());

            }

            SaveEvent?.Invoke(SelectedProductModel);
          
           // await Send(new ProductToShellEvent());

        }

        public async Task<bool> Send(EventBase? request)
        {
          
            if (request is null)
            {
                return false;
            }
            await EventAggregator.PublishOnUIThreadAsync(request);
            return await request.TaskCompletionSource.Task;
        }

        public void Save()
        {
            if (ProductModels.Count > 0)
            {
                SaveConfigData.SaveConfig<ProductModel>(Paths.ProductConfigPaths, ProductModels.ToArray());
            }
        }

        public  void LoadCad()
        {
            // 打开文件选择对话框
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "DXF files (*.dxf)|*.dxf|All files (*.*)|*.*",
                Title = "选择DXF文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                // 选中的文件路径
                string sourceFilePath = openFileDialog.FileName;

                // 目标路径（可以根据需要更改为你希望的路径）
                string targetPath = Paths.DxfSavePaths;

                string fileName = System.IO.Path.GetFileNameWithoutExtension(sourceFilePath);


                //cad文件名称
                SelectedProductModel.CADName = fileName;

                // 确保目标目录存在
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }

                // 构建目标文件路径
                string targetFilePath = Path.Combine(targetPath, Path.GetFileName(sourceFilePath));

                try
                {
                    // 复制文件
                    File.Copy(sourceFilePath, targetFilePath, true);
                    MessageBox.Show("文件导入成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"文件导入失败：{ex.Message}");
                }
            }
        }


        public void EditCad()
        {
            if (SelectedProductModel.CADName is null || SelectedProductModel.CADName==string.Empty)
            {
                MessageBox.Show("未找到cad文件");
                return;
            }

             CADViewModel CADViewModel = new CADViewModel();
            CADViewModel.FileName = SelectedProductModel.CADName;
            WindowManager.ShowWindowAsync(CADViewModel);
        }

        public void Create()
        {
            var createViewModel =  new CreateProductViewModel();
            ProductModel newProductModel = new ProductModel();


            Common.AutoMapProperties(SelectedProductModel, newProductModel);
            createViewModel.CreateProductModel = newProductModel;
            createViewModel.CreateProductModel.ControlName = string.Empty;



            WindowManager.ShowDialogAsync(createViewModel);
            if (createViewModel.Product != null) 
            {
                SelectedProductModel = createViewModel.Product;
                ProductModels.Add(SelectedProductModel);
                SelectedItem = SelectedProductModel;
            }
        }

        public void Remove()
        {
            var res = MessageBoxX.Show("确定是否删除？","警告",System.Windows.MessageBoxButton.YesNo,  MessageBoxIcon.Warning);
            if (res == System.Windows.MessageBoxResult.Yes)
            {
                ProductModels.Remove(SelectedProductModel);
                Save();
                DeleteEvent?.Invoke(SelectedProductModel);
            }
            
        }

       

        public  void Load()
        {
            var productConfigs = ReadConfigData.GetParaConfigs<ProductModel>(Paths.ProductConfigPaths);

            if (productConfigs != null)
            {
                ProductModels = new ObservableCollection<ProductModel>(productConfigs);
                SearchLastSelecteItem();
            }
            //ProductModel = productConfigs?.FirstOrDefault(config => config.ControlName.Contains("")) ?? new ProductModel();

            //2.获取工具信息

            //var toolConfigs = ReadConfigData.GetParaConfigs<ToolModel>(Paths.ToolConfigPaths);
            //ToolModel = toolConfigs?.FirstOrDefault(config => config.ControlName.Contains("")) ?? new ToolModel();
        }


        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <returns></returns>
        public async void Send(object? request)
        {         
            
            await EventAggregator.PublishOnUIThreadAsync(request);
            
        }

        /// <summary>
        /// 设置全部为未选中状态
        /// </summary>
        private void SetAllProductUnselected()
        {
            if (ProductModels.Count > 0)
            {
                foreach (var product in ProductModels)
                {
                    product.IsLastSelected = false;
                }
            }
        }

        /// <summary>
        /// 查找最后一个选中的产品
        /// </summary>
        private void SearchLastSelecteItem()
        {
            if (ProductModels.Count > 0)
            {
                foreach (var product in ProductModels)
                {
                    if (product.IsLastSelected)
                    {
                        SelectedProductModel = product;
                        SelectedItem = SelectedProductModel;
                        break;
                    }
                }
            }
        }


        public void Rename()
        {
            var dialog = new InputDialog("重命名", "请输入新的名称：");
            if (dialog.ShowDialog() == true)
            {
                string input = dialog.InputText;

                RenameEvent?.Invoke(SelectedProductModel.ControlName,input);
                // 处理输入
                SelectedProductModel.ControlName = input;

               
            }
        }
    }
}
